package ink.lovejinhu.leetcode;

import org.junit.Test;

import java.util.HashMap;

/**
 * @author jinhu
 * created 2021-04-25 17:50
 */
public class Solution_0001 {
    @Test
    public void test() {

    }

    /**
     * target=nums[i]+nums[j]
     *
     * @param nums
     * @param target
     * @return
     */
    public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (target == nums[i] + nums[j]) {
                    result[0] = i;
                    result[1] = j;
                    return result;
                }
            }
        }
        return result;
    }

    /**
     * 优化hash
     *
     * @param nums
     * @param target
     * @return
     */
    public int[] twoSum01(int[] nums, int target) {
        int[] result = new int[2];
        HashMap<Integer, Integer> hashMap = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (hashMap.containsKey(nums[i])) {
                result[0]=hashMap.get(nums[i]);
                result[1]=i;
            }
            hashMap.put(target - nums[i], i);
        }
        return result;


    }

}
